package com.tjw.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.tjw.pojo.Permission;
import com.tjw.pojo.Role;
import com.tjw.pojo.User;
import com.tjw.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author tjw
 * @Date 2020/10/16
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取user对象
        User user = userService.findByUsername(username);
        if (user == null) {
            return null;
        }
        //封装当前用户的角色和权限
        List<GrantedAuthority> list = new ArrayList<>();
        //获取当前用户的权限和对应的角色
        Set<Role> roles = user.getRoles();
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                //获取当前角色的关键字
                String keyword = role.getKeyword();
                //为当前用户授予角色
                list.add(new SimpleGrantedAuthority(keyword));
                //获取当前角色对应所有权限信息
                Set<Permission> permissions = role.getPermissions();
                //遍历所有权限数组
                for (Permission permission : permissions) {
                    //获取权限对应的关键字
                    String permissionKeyword = permission.getKeyword();
                    //为角色添加权限
                    list.add(new SimpleGrantedAuthority(permissionKeyword));
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
    }

}
